package com.loopy.fruns.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCDruidUtils {
    private static DataSource ds;
    private static ThreadLocal<Connection> threadLocalCon = new ThreadLocal<>();

    static {
        Properties properties = new Properties();
        try {

            properties.load(JDBCDruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //public static Connection getConnection() throws SQLException {
    //Connection connection = ds.getConnection();
    //return connection;
//    }
    public static Connection getConnection()  {
        Connection connection = threadLocalCon.get();
        if(connection==null){
            try {
                connection=ds.getConnection();
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            threadLocalCon.set(connection);
        }
        return connection;
    }
    public static void commit(){
        Connection connection = threadLocalCon.get();
        if(connection!=null){
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        threadLocalCon.remove();
    }
    public static void rollback(){
        Connection connection = threadLocalCon.get();
        if(connection!=null){
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        threadLocalCon.remove();
    }


    public static void close(ResultSet set, Statement statement, Connection connection) {

        try {
            if (set != null) {
                set.close();
                if (connection != null) {
                    connection.close();
                }
                if (statement != null) {
                    statement.close();
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
